﻿using System;
using System.Diagnostics;
using System.Linq;
using System.Windows.Forms;
using TfsCommitMonitor.Properties;
using TfsCommitMonitor.Tfs;
using Change = Microsoft.TeamFoundation.VersionControl.Client.Change;

namespace TfsCommitMonitor
{
	internal partial class ChangeSetDetailDialog : Form
	{
		private readonly Changeset _changeset;
		internal ChangeSetDetailDialog(Changeset changeset)
		{
			InitializeComponent();
			_changeset = changeset;
			InitializeListView();
		}
	
		private void InitializeListView()
		{
			_fileColumn.Text = Resources.ChangeSetDetailDialog_TfsListView_Header_File;
            _actionColumn.Text = Resources.ChangeSetDetailDialog_TfsListView_Header_Action;
			tfsListView1.DoubleClick += (sender, e) => ListViewDoubleClick();
		}

		private void ListViewDoubleClick()
		{
			var selectedItem =
				tfsListView1.SelectedItems
				.Cast<ListViewItem>()
				.SingleOrDefault();

			if (selectedItem != null)
			{
				var change = selectedItem.Tag as Change;

				var lastChangeFilePath = 
					new TfsBusiness().DownloadChanges(_changeset.CollectionUri, _changeset.ProjectPath, change);
				var currentVersionFilePath =
					TfsBusiness.GetTempFilePath(change);

                using (var process = new Process())
                {
                    process.StartInfo = new ProcessStartInfo
                    {
                        FileName = @"C:\Program Files (x86)\WinMerge\WinMergeU.exe",
                        Arguments = String.Format(@"""{0}"" ""{1}""", lastChangeFilePath, currentVersionFilePath),
                    };
                    process.Start();
                }
			}
		}

		Change[] _changes;

		private void ChangeSetDetailDialog_Load(object sender, EventArgs e)
		{
			_changes = _changeset.GetTfsChanges();
			tfsListView1.Items.AddRange(
				_changes
				.Select(CreateListViewItem)
				.ToArray());

			tfsListView1.Columns[0].Width = ClientSize.Width - 100;
		}

		private static ListViewItem CreateListViewItem(Change change)
		{
			var listViewItem = new ListViewItem(change.Item.ServerItem)
			{
				Tag = change,
			};

			listViewItem.SubItems.Add(change.ChangeType.ToString());

			return listViewItem;
		}
	}
}
